package huawei_security_go

import (
	"errors"
)

var (
	defaultSalt = []byte{16, 51, 51, 53, 11, 24, 10, 14, 24, 73, 15, 23, 31, 235, 163, 184}
)

type LocalSecurityDecryptor struct {
	ciphers map[string]interface{}
}

func (a *LocalSecurityDecryptor) DecryptCipher(ciphers interface{}) (string, error) {
	ciphersObj, ok := ciphers.(Ciphers)
	if !ok || &ciphersObj == nil {
		return "", errors.New("cast to Ciphers failed")
	}

	rootKey, err := GetRootKey(ciphersObj.Sysconfig, ciphersObj.Config)
	if err != nil {
		return "", errors.New("get root key failed: " + err.Error())
	}

	workKeyCp := NewCipherPart(ciphersObj.WorkeyCipher)
	workKey, err := Decrypt(workKeyCp.cipherTextHex, workKeyCp.ivHex, rootKey, defaultSalt)
	if err != nil {
		return "", errors.New("decrypt work key failed: " + err.Error())
	}

	pwdCp := NewCipherPart(ciphersObj.PasswdCipher)
	password, err := Decrypt(pwdCp.cipherTextHex, pwdCp.ivHex, workKey, defaultSalt)
	if err != nil {
		return "", errors.New("decrypt cipher text failed: " + err.Error())
	}

	return password, nil
}
